package org.odiem.stacks.opends;

import java.util.Properties;

import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.LDAPConnectionFactory;
import org.forgerock.opendj.ldap.LDAPOptions;
import org.odiem.api.OdmStack;
import org.odiem.api.OdmStackFactory;
import org.odiem.sdk.exceptions.OdmException;

public class StackFactoryImpl implements OdmStackFactory {

	private Properties properties;
	private LDAPOptions ldapOptions = new LDAPOptions();

	public StackFactoryImpl(Properties properties) {
		this.properties = properties;
		//TODO
		//ldapOptions.setTCPNIOTransport(new TCPNIOTransport());
	}

	@Override
	public Properties getProperties() {
		return properties;
	}

	@Override
	public OdmStack createStack(String host, int port) throws OdmException {
		return createStack(host, port, null, null);
	}

	@Override
	public OdmStack createStack(String host, int port, String username,
			String password) throws OdmException {
		try {

			// opends
			LDAPConnectionFactory factory = new LDAPConnectionFactory(host,
					port, ldapOptions);
			Connection connection = factory.getConnection();
			if (username != null) {
				connection.bind(username, password.toCharArray());
			}
			return new StackImpl(connection, username);

		} catch (Exception e) {
			throw new OdmException(e);
		}
	}
}
